package com.example.administrator.officeplatform.Audit;

import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

import com.example.administrator.officeplatform.Activity.UpLoadImagesActivity;
import com.example.administrator.officeplatform.Image.ImagePagerActivity;
import com.example.administrator.officeplatform.MyApplication;
import com.example.administrator.officeplatform.R;
import com.example.administrator.officeplatform.base.BaseActivity;
import com.example.administrator.officeplatform.bean.Fileinfo;
import com.example.administrator.officeplatform.bean.ReimbursementVoInfo;
import com.example.administrator.officeplatform.kj.IpUtil;
import com.example.administrator.officeplatform.utils.JsonUtil;
import com.example.administrator.officeplatform.utils.UILImageLoader;
import com.nostra13.universalimageloader.cache.disc.impl.UnlimitedDiskCache;
import com.nostra13.universalimageloader.cache.disc.naming.HashCodeFileNameGenerator;
import com.nostra13.universalimageloader.cache.memory.impl.LruMemoryCache;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoaderConfiguration;
import com.nostra13.universalimageloader.core.assist.QueueProcessingType;
import com.nostra13.universalimageloader.core.download.BaseImageDownloader;
import java.io.File;
import java.io.IOException;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import butterknife.Bind;
import butterknife.ButterKnife;
import cn.finalteam.galleryfinal.CoreConfig;
import cn.finalteam.galleryfinal.FunctionConfig;
import cn.finalteam.galleryfinal.GalleryFinal;
import cn.finalteam.galleryfinal.ImageLoader;
import cn.finalteam.galleryfinal.ThemeConfig;
import cn.finalteam.toolsfinal.StorageUtils;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

public class ShowImageActivity extends BaseActivity {
    @Bind(R.id.rv_image)
    RecyclerView rv_image;
    @Bind(R.id.toolbar)
    Toolbar toolbar;
    private Intent mIntent;
    private Context mContext;
    private List<Fileinfo> ls_file = new ArrayList<>();
    private List<String> ls_fileStr = new ArrayList<>();
    private ReimbursementVoInfo reimbursementVoInfo = new ReimbursementVoInfo();
    private ReimbursementVoInfo newInfo;
    private ProgressDialog mProgressDialog;
    private OkHttpClient mOkHttpClient= new OkHttpClient();
    private Button btn_image;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    protected void setContentView() {
        setContentView(R.layout.activity_show_image);
    }

    @Override
    protected void initViews() {
        ButterKnife.bind(this);
        mContext=this;
        mIntent = getIntent();

        //设置布局管理器
        rv_image.setLayoutManager(new GridLayoutManager(mContext,3));
        rv_image.setHasFixedSize(true);
        rv_image.setItemAnimator(new DefaultItemAnimator());
        btn_image  = (Button)findViewById(R.id.btn_image);
        initConfig();
        init();
        btn_image.setVisibility(View.GONE);

        String who = (String) mIntent.getExtras().get(
                "who");
        String ProcessState = (String) mIntent.getExtras().get(
                "ProcessState");
        if (who.equals("1")){
            /**判断是否可以提交*/

            String processState =String.valueOf(ProcessState);
            if (processState.equals("1")){
                btn_image.setVisibility(View.VISIBLE);
            }

        }
        reimbursementVoInfo = (ReimbursementVoInfo) mIntent.getExtras().get(
                "ReimbursementVoInfo");
    }

    @Override
    protected void initData() {
//        String[] images= new String[] {
//                "http://img.zcool.cn/community/0166c756e1427432f875520f7cc838.jpg",
//                "http://img.zcool.cn/community/018fdb56e1428632f875520f7b67cb.jpg",
//                "http://img.zcool.cn/community/01c8dc56e1428e6ac72531cbaa5f2c.jpg",
//                "http://img.zcool.cn/community/01fda356640b706ac725b2c8b99b08.jpg",
//                "http://img.zcool.cn/community/01fd2756e142716ac72531cbf8bbbf.jpg",
//                "http://img.zcool.cn/community/0114a856640b6d32f87545731c076a.jpg"};
//
//        for(int i=0;i<6;i++){
//            Fileinfo fileinfo = new Fileinfo();
//            fileinfo.setFileUrl(images[i]);
//            ls_file.add(fileinfo);
//            ls_fileStr.add(images[i]);
//        }
        getdata();




    }

    @Override
    protected void initEvents() {
        toolbar.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        btn_image.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent();
                intent.setClass(getApplicationContext(), UpLoadImagesActivity.class);
                Bundle bundle = new Bundle();
                bundle.putSerializable("ReimbursementVoInfo", reimbursementVoInfo);
                intent.putExtras(bundle);
                startActivityForResult(intent, 1);
            }
        });
    }

    /**
     *获取数据
     *@author Wangzhiqiang
     *Created on 2017/12/21 18:58
     */
    private void getdata(){
        mProgressDialog = ProgressDialog.show(mContext, null, "正在加载中...");
        mProgressDialog.setCancelable(true);
        mProgressDialog.setCanceledOnTouchOutside(false);
        mOkHttpClient = new OkHttpClient();
        String id = reimbursementVoInfo.getId();
        Request request = new Request.Builder()
                .url(IpUtil.getIP()+"/reimbursement/reimbursement/getReimbursementById/"+reimbursementVoInfo.getId())
                .header("cookie", MyApplication.getMsession())
                .build();

        Call call = mOkHttpClient.newCall(request);

        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                mProgressDialog.dismiss();
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        Toast.makeText(mContext, "连接异常", Toast.LENGTH_SHORT).show();
                    }
                });
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                mProgressDialog.dismiss();
                String str = response.body().string();
                if(str.indexOf("reimbursementCode")>=0) {
                    newInfo = JsonUtil.getPerson(str, ReimbursementVoInfo.class);
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            showImage();
                        }
                    });

                }else{
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            Toast.makeText(mContext, "查询报销单信息出现错误", Toast.LENGTH_SHORT).show();

                        }
                    });
                }
            }
        });

    }

    private void showImage(){
        ls_file=newInfo.getFileVoList();
        reimbursementVoInfo.setFileVoList(ls_file);
        if(ls_file!=null){
            if(ls_file.size()>0){
                for(int i=0;i<ls_file.size();i++){
                    ls_fileStr.add(IpUtil.getImage_address()+ls_file.get(i).getFileUrl());
                }
                ShowImageAdapter showImageAdapter = new ShowImageAdapter(ShowImageActivity.this,ls_file);
                rv_image.setAdapter(showImageAdapter);
                showImageAdapter.setOnRecyclerViewListener(new ShowImageAdapter.OnRecyclerViewListener() {
                    @Override
                    public void onItemClick(int position) {
                        Intent intent = new Intent(mContext, ImagePagerActivity.class);
                        intent.putExtra(ImagePagerActivity.EXTRA_IMAGE_INDEX, position);
                        intent.putStringArrayListExtra(ImagePagerActivity.EXTRA_IMAGE_URLS, (ArrayList<String>) ls_fileStr);
                        startActivity(intent);
                    }

                    @Override
                    public boolean onItemLongClick(int position) {
                        return false;
                    }
                });            }
        }
    }

    /**
     *照相机框架配置
     *@author Wangzhiqiang
     *Created on 2017/12/18 14:14
     */
    private void initConfig() {
        //配置主题
        //ThemeConfig.CYAN
        ThemeConfig theme = new ThemeConfig.Builder()
                .build();
        //配置功能
        FunctionConfig functionConfig = new FunctionConfig.Builder()
                .setEnableCamera(true)
                .setEnableEdit(true)
                .setEnableCrop(true)
                .setEnableRotate(true)
                .setCropSquare(true)
                .setEnablePreview(false)
                .build();

        //配置imageloader
        ImageLoader imageloader = new UILImageLoader();
        //设置核心配置信息
        CoreConfig coreConfig = new CoreConfig.Builder(getApplicationContext(), imageloader, theme)
                .setFunctionConfig(functionConfig)
                .build();
        GalleryFinal.init(coreConfig);
    }

    private void init() {
        File cacheDir = StorageUtils.getCacheDirectory(getApplicationContext());
        ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(getApplicationContext())
                .memoryCacheExtraOptions(480, 800) // default = device screen dimensions
                .diskCacheExtraOptions(480, 800, null)
                .threadPoolSize(3) // default
                .threadPriority(Thread.NORM_PRIORITY - 2) // default
                .tasksProcessingOrder(QueueProcessingType.FIFO) // default
                .denyCacheImageMultipleSizesInMemory()
                .memoryCache(new LruMemoryCache(2 * 1024 * 1024))
                .memoryCacheSize(2 * 1024 * 1024)
                .memoryCacheSizePercentage(13) // default
                .diskCache(new UnlimitedDiskCache(cacheDir)) // default
                .diskCacheSize(50 * 1024 * 1024)
                .diskCacheFileCount(100)
                .diskCacheFileNameGenerator(new HashCodeFileNameGenerator()) // default
                .imageDownloader(new BaseImageDownloader(getApplicationContext())) // default
                .defaultDisplayImageOptions(DisplayImageOptions.createSimple()) // default
                .writeDebugLogs()
                .build();
        com.nostra13.universalimageloader.core.ImageLoader.getInstance().init(config);
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {

        if (resultCode == 1){
            getdata();
        }
//        if (resultCode == 1){
//            reimbursementVoInfo = (ReimbursementVoInfo)data.getExtras().get("ReimbursementVoInfo");
//        }
    }
}
